class Message {
    static init(window) {

        window.cppMessage = function (cmd, data) {
            Message.cppMessage(cmd, data)
        }
        console.log('window.cppMessage init sucess!')
        //must init at vue
    }

    static finish(name) {
        var data = {
            name: name
        }
        Message.jsMessage('WebFinish', JSON.stringify(data))
    }

    //回调函数
    static g_cppMessageCallbackMap = new Map()

    constructor() { }

    static addCppMessageCallback(cmd, callback, reset = true) {
        if (reset) {
            Message.removeCppMessageCallback(cmd)
        }
        if (!Message.g_cppMessageCallbackMap.has(cmd)) {
            Message.g_cppMessageCallbackMap.set(cmd, callback)
        }
    }

    static removeCppMessageCallback(cmd) {
        if (Message.g_cppMessageCallbackMap.has(cmd)) {
            Message.g_cppMessageCallbackMap.delete(cmd)
        }
    }

    //接收消息
    static cppMessage(cmd, data) {
        if (Message.g_cppMessageCallbackMap.has(cmd)) {
            Message.g_cppMessageCallbackMap.get(cmd)(data)
        } else {
            console.log('please register:', cmd)
        }
    }

    //发送消息
    static jsMessage(cmd, data) {

        if (typeof window.cppFunction === 'function') {
            window.cppFunction(cmd, data)
        }
    }

    //发送返回值消息
    static jsReturnMessage(cmd, data) {
        if (typeof window.cppReturnFunction === 'function') {
            window.cppReturnFunction(cmd, data)
        }
    }
}

export { Message }
